package org.zhiyootech.base.filter;

import io.vertx.core.http.HttpServerRequest;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Provider
public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

    @Context
    UriInfo info;
    @Context
    HttpServerRequest request;
    AtomicInteger _id = new AtomicInteger(0);
    AtomicInteger requestId = new AtomicInteger(0);

    @Override
    public void filter(ContainerRequestContext context) throws IOException {
        final String method = context.getMethod();
        final String path = info.getPath();
        final String address = request.remoteAddress().toString();
        final long id = requestId.incrementAndGet();
        context.setProperty("prop", id);
        log.info("Request {} {} from IP {}", method, path, address);
    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        String LOGGING_ID_PROPERTY = "prop";
        String RESPONSE_PREFIX = "responsePrefix";

        final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
        final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();

        final StringBuilder b = new StringBuilder();

        b.append("text");

        printResponseLine(b, "Client response received", id, responseContext.getStatus());
        printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());
    }

    private void printResponseLine(StringBuilder b, String string, long id, int status) {
        log.info(b.toString() + id);
    }

    private void printPrefixedHeaders(StringBuilder b, long id, String string, MultivaluedMap<String, Object> headerMap) {
        log.info(b.toString() + id);
    }

}
